package com.jingdianjichi.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jingdianjichi.subject.common.enums.IsDeletedFlageEnum;
import com.jingdianjichi.subject.domain.convert.SubjectCategoryConverter;
import com.jingdianjichi.subject.domain.entity.SubjectCategoryBo;
import com.jingdianjichi.subject.domain.entity.SubjectLabelBo;
import com.jingdianjichi.subject.domain.service.SubjectCategoryDomainService;
import com.jingdianjichi.subject.domain.util.CacheUtil;
import com.jingdianjichi.subject.infra.basic.entity.SubjectCategory;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.service.SubjectCategoryService;
import com.jingdianjichi.subject.infra.basic.service.SubjectLabelService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectCategoryDomainServiceImpl implements SubjectCategoryDomainService {

    @Resource
    private SubjectCategoryService subjectCategoryService;
    @Resource
    private SubjectMappingService subjectMappingService;
    @Resource
    private SubjectLabelService subjectLabelService;
    @Resource
    private ThreadPoolExecutor labelThreadPool;

    @Resource
    private CacheUtil cacheUtil;
    public void add(SubjectCategoryBo subjectCategoryBo) {
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.add.dto:{}", JSON.toJSONString(subjectCategoryBo));
        }
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlageEnum.UN_DELETE.getCode());
        subjectCategoryService.insert(subjectCategory);
    }


    public List<SubjectCategoryBo> queryCategory(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlageEnum.UN_DELETE.getCode());

        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        List<SubjectCategoryBo> boList = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryList);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryPrimaryCategory.boList:{}", JSON.toJSONString(boList));
        }
        boList.forEach(bo -> {
            Integer subjectCount = subjectCategoryService.querySubjectCount(bo.getId());
            bo.setCount(subjectCount);
        });
        return boList;
    }

    @Override
    public Boolean update(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBo);
        int count = subjectCategoryService.update(subjectCategory);

        return count > 0;
    }

    @Override
    public Boolean delete(SubjectCategoryBo subjectCategoryBo) {
        SubjectCategory subjectCategory = SubjectCategoryConverter.INSTANCE
                .convertBoToCategory(subjectCategoryBo);
        subjectCategory.setIsDeleted(IsDeletedFlageEnum.DELETE.getCode());
        int count = subjectCategoryService.update(subjectCategory);

        return count > 0;

    }

    /**
     * 线程池第一种实现方式
     * @param category
     * @return
     */
//    @SneakyThrows
//    @Override
//    public List<SubjectCategoryBo> queryCategoryAndLabel(SubjectCategoryBo subjectCategoryBo) {
//        //查询单前大类下所有分类
//        SubjectCategory subjectCategory = new SubjectCategory();
//        subjectCategory.setParentId(subjectCategoryBo.getId());
//        subjectCategory.setIsDeleted(IsDeletedFlageEnum.UN_DELETE.getCode());
//        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
//        if (log.isInfoEnabled()) {
//            log.info("SubjectCategoryController.queryCategoryAndLabel.subjectCategoryList:{}"
//                    , JSON.toJSONString(subjectCategoryList));
//        }
//        List<SubjectCategoryBo> CategoryBoList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
//        //一次获取标签信息
//        List<FutureTask<Map<Long, List<SubjectLabelBo>>>> futureTaskList = new LinkedList<>();
//        // 线程池并发调用
//        Map<Long, List<SubjectLabelBo>> map = new HashMap<>();
//        CategoryBoList.forEach(category -> {
//            FutureTask<Map<Long, List<SubjectLabelBo>>> futureTask = new FutureTask<>(() ->
//                    getLabelBoList(category));
//            futureTaskList.add(futureTask);
//            labelThreadPool.submit(futureTask);
//        });
//        for (FutureTask<Map<Long, List<SubjectLabelBo>>> futureTask : futureTaskList) {
//            Map<Long, List<SubjectLabelBo>> resultMap = futureTask.get();
//            if (CollectionUtils.isEmpty(resultMap)) {
//                continue;
//            }
//            map.putAll(resultMap);
//        }
//        CategoryBoList.forEach(categoryBo -> {
//            categoryBo.setLabelBoList(map.get(categoryBo.getId()));
//        });
//        return CategoryBoList;
//    }
    /**
     * 线程池第二种实现方式
     *
     * @return
     */
    @SneakyThrows
    @Override
    public List<SubjectCategoryBo> queryCategoryAndLabel(SubjectCategoryBo subjectCategoryBo) {
       Long id = subjectCategoryBo.getId();
        String cacheKey="categoryAndLabel."+subjectCategoryBo.getId();
        List<SubjectCategoryBo> subjectCategoryBos = cacheUtil.getResult(cacheKey,
                SubjectCategoryBo.class, (key) -> getSubjectCategoryBos(id));
        return subjectCategoryBos;
    }

    private List<SubjectCategoryBo> getSubjectCategoryBos(Long categoryId) {
        //查询单前大类下所有分类
        SubjectCategory subjectCategory = new SubjectCategory();
        subjectCategory.setParentId(categoryId);
        subjectCategory.setIsDeleted(IsDeletedFlageEnum.UN_DELETE.getCode());
        List<SubjectCategory> subjectCategoryList = subjectCategoryService.queryCategory(subjectCategory);
        if (log.isInfoEnabled()) {
            log.info("SubjectCategoryController.queryCategoryAndLabel.subjectCategoryList:{}"
                    , JSON.toJSONString(subjectCategoryList));
        }
        List<SubjectCategoryBo> CategoryBoList = SubjectCategoryConverter.INSTANCE.convertBoToCategory(subjectCategoryList);
        //一次获取标签信息
        Map<Long,List<SubjectLabelBo>> map = new HashMap<>();
        List<CompletableFuture<Map<Long, List<SubjectLabelBo>>>> completableFutureList  = CategoryBoList.stream().map(category ->
                CompletableFuture.supplyAsync(() -> getLabelBoList(category), labelThreadPool)
        ).collect(Collectors.toList());
        completableFutureList.forEach(future->{
            try {
                Map<Long,List<SubjectLabelBo>> resultMap = future.get();
                map.putAll(resultMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        CategoryBoList.forEach(categoryBo -> {
            categoryBo.setLabelBoList(map.get(categoryBo.getId()));
        });
        return CategoryBoList;
    }

    private Map<Long, List<SubjectLabelBo>> getLabelBoList(SubjectCategoryBo category) {
        Map<Long, List<SubjectLabelBo>> labelBoMap = new LinkedHashMap<>();
        SubjectMapping subjectMapping = new SubjectMapping();
        //根据categoryid从mapping表获取lable集合
        subjectMapping.setCategoryId(category.getId());
        List<SubjectMapping> mappingList = subjectMappingService.queryLabelId(subjectMapping);
        if (CollectionUtils.isEmpty(mappingList)) {
            return null;
        }
        //从lable集合中表获取lableid集合
        List<Long> labelIdList = mappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        //从lable表获取lable信息
        List<SubjectLabel> labelList = subjectLabelService.batchQueryById(labelIdList);
        List<SubjectLabelBo> labelBoList = new LinkedList<>();
        labelList.forEach(label -> {
            SubjectLabelBo subjectLabelBo = new SubjectLabelBo();
            subjectLabelBo.setId(label.getId());
            subjectLabelBo.setLabelName(label.getLabelName());
            subjectLabelBo.setCategoryId(label.getCategoryId());
            subjectLabelBo.setSortNum(label.getSortNum());
            labelBoList.add(subjectLabelBo);
        });
        labelBoMap.put(category.getId(), labelBoList);
        return labelBoMap;
    }
}
